/*
 * 文件名：EffectPlanController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：chenhan
 * 修改时间：2020年1月17日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.bpa.domain.EffectPlanDomain;
import top.infopub.mgr.bpa.service.EffectPlanService;
import top.infopub.mgr.bpa.service.ProContractService;
import top.infopub.mgr.bpa.vo.EffectPlanVo;
import top.infopub.mgr.bpa.vo.ProContractVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.web.BuildInfoController;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.bpa.EffectPlan;
import top.infopub.model.bpa.EffectPlanDetail;
import top.infopub.model.bpa.ProContract;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * @author chenhan
 * @version 2020年1月10日
 * @see BuildInfoController
 * @since
 */
@Controller
@RequestMapping("/effectPlan")
public class EffectPlanController extends GenericFlowController {

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private EffectPlanService effectPlanService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private ProContractService proContractService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 跳转列表页
     *
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "bpa/lay-effectPlan-list";
    }

    /**
     * 创效计划列表数据
     *
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<EffectPlanDomain> queryDataByCondition(EffectPlanVo effectPlanVo,
                                                        ParamPage paramPage) {
        Page<EffectPlanDomain> page = new Page<EffectPlanDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (effectPlanVo.getEndDate() != null) {
            effectPlanVo.setEndDate(DateUtils.addDays(effectPlanVo.getEndDate(), 1));
        }
        page = effectPlanService.selectPageByDomainWhere(page, effectPlanVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 创效计划-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<EffectPlanDomain> queryMyCheckDataByCondition(EffectPlanVo effectPlanVo,
                                                               ParamPage paramPage) {
        Page<EffectPlanDomain> page = new Page<EffectPlanDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (effectPlanVo.getEndDate() != null) {
            effectPlanVo.setEndDate(DateUtils.addDays(effectPlanVo.getEndDate(), 1));
        }
        effectPlanVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = effectPlanService.selectMyCheckByDomainWhere(page, effectPlanVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 创效计划-新增
     *
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可公司年度预算的公司年度预算记录
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询所有项目合同
        List<ProContract> contractList = proContractService.selectAllContracts(null, null);
        request.setAttribute("contractList", contractList);
        return "bpa/lay-effectPlan-add";
    }

    /**
     * 根据id查询项目合同记录记录
     *
     * @param id
     * @return
     */
    @RequestMapping("/getProContractById")
    @ResponseBody
    public Map<String, Object> getProContractById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String[] split = id.split("\\_");
            ProContractVo proContractVo = proContractService.queryById(split[3]);
            if (proContractVo != null) {
                map.put("proContractVo", proContractVo);
            }
        }
        catch (Exception e) {
            log.error("查询合同记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 创效计划-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(HttpServletRequest request, EffectPlan effectPlan) {
        //根据项目id,查出项目的其他信息  此时的proCode存放的时项目合同的Id
        String proContractId = effectPlan.getProCode();
        String[] split = proContractId.split("\\_");
        //ProContract proContract = proContractService.selectByPrimaryKey(proContractId);
        effectPlan.setProCode(split[0]);
        effectPlan.setProName(split[1]);
        effectPlan.setTypes("1");
        effectPlan.setSgCityId(split[2]);
        String effectPlanId = IdFactory.getUUIDUpper();
        effectPlan.setId(effectPlanId);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        effectPlan.setHrStaffApplyId(vo.getHrStaffId());
        effectPlan.setAddBy(vo.getId());
        effectPlan.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("bpa_effect_plan");
        effectPlan.setCodes(codes);
        effectPlan.setProcessId(IdFactory.getUUIDUpper());
        //设置审批状态
        effectPlan.setProcessStatus("1");
        effectPlan.setUptBy(vo.getId());
        effectPlan.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子表数据处理
        String[] monthsArray = request.getParameterValues("months");
        String[] monthPlanAmountArray = request.getParameterValues("monthPlanAmount");
        List<EffectPlanDetail> detailList = new LinkedList<>();
        for (int i = 0; i < monthsArray.length; i++ ) {
            EffectPlanDetail effectPlanDetail = new EffectPlanDetail();
            String detailId = IdFactory.getUUIDUpper();
            effectPlanDetail.setId(detailId);
            effectPlanDetail.setMonths(Integer.parseInt(monthsArray[i]));
            effectPlanDetail.setMonthPlanAmount(new BigDecimal(monthPlanAmountArray[i]));
            effectPlanDetail.setEffectPlanId(effectPlanId);
            effectPlanDetail.setAddBy(vo.getId());
            effectPlanDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            detailList.add(effectPlanDetail);
        }

        effectPlanService.save(effectPlan, detailList);
        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
            "商务管理 -商务事项-新增创效计划：项目名=" + effectPlan.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 根据id查询创效计划详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 投建项目id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        EffectPlanVo effectPlan = effectPlanService.queryById(id);
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setProjectCode(effectPlan.getProCode());
        orgInfo.setState(1);
        List<OrgInfo> orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        if (orgInfos.size() > 0) {
            effectPlan.setOrgProName(orgInfos.get(0).getCompName());
            effectPlan.setHrOrgProId(orgInfos.get(0).getId());
            OrgInfo parentOrgInfo = new OrgInfo();
            parentOrgInfo.setId(orgInfos.get(0).getParentId());
            parentOrgInfo.setState(1);
            List<OrgInfo> parentOInfos = orgInfoService.selectByEntityWhere(parentOrgInfo);
            if (parentOInfos.size() > 0) {
                effectPlan.setOrgAreName(parentOInfos.get(0).getCompName());
                effectPlan.setHrOrgAreaId(parentOInfos.get(0).getId());
            }
        }
        request.setAttribute("modelDetail", effectPlan);
        map.put("effectPlan", effectPlan);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, effectPlan.getProcessId());
        return new ModelAndView("bpa/lay-effectPlan-detail", map);
    }

    /**
     * 创效计划-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        EffectPlanVo effectPlan = effectPlanService.queryById(id);
        request.setAttribute("effectPlan", effectPlan);
        return "bpa/lay-effectPlan-copy";
    }

}
